import request from '@/utils/request'
import type { ApiResponse , PageResult} from '@/types/api'



// 登录表单
export interface LoginForm {
  username: string
  password: string
}

// 注册表单
export interface RegisterForm {
  username: string
  password: string
}

// 登录结果
export interface LoginResult {
  token: string
  userId: string
  username: string
  roles: string[]
  permissions: string[]
}

// 用户信息
export interface UserInfo {
  id: string
  username: string
  phone: string | null
  balance: number
  status: number
  createTime: string
  updateTime: string
}

// 分页查询参数
export interface UserQuery {
  pageNum: number
  pageSize: number
  username?: string
  phone?: string
  status?: number
}



// 登录
export const login = (data: LoginForm) => {
  return request.post<ApiResponse<LoginResult>>('/users/login', data)
}

// 获取当前用户信息
export const getUserInfo = () => {
  const userId = sessionStorage.getItem('userId')
  return request.get<UserInfo>(`/users/${userId}`)
}

// 退出登录
export const logout = () => {
  return request.post<ApiResponse<void>>('/users/logout')
}

// 注册
export const register = (data: RegisterForm): Promise<ApiResponse<string>> => {
  return request.post('/users/register', data)
}

// 获取用户列表
export const getUserList = (params: UserQuery) => {
  return request.get<PageResult<UserInfo>>('/users/page', { params })
}

// 获取用户详情
export const getUserDetail = (id: number) => {
  return request.get<ApiResponse<UserInfo>>(`/users/${id}`)
}

// 更新用户信息
export const updateUser = (id: number, data: Partial<UserInfo>) => {
  return request.put<ApiResponse<void>>(`/users/${id}`, data)
}

// 扣减余额
export const deductMoney = (pw: string, amount: number) => {
  return request.put<ApiResponse<void>>('/users/money/deduct', null, {
    params: { pw, amount }
  })
}

// 创建用户
export const createUser = (data: Partial<UserInfo> & { password: string }) => {
  return request.post<ApiResponse<void>>('/users', data)
}


